#include "LPXX.h"
#include "CAN1.h"
#include "common.h"

void LPXX_Start_Measure(uint16_t canid)
{
	uint8_t buf[8] = {0X55,0X05,0X00,0X00,0X00,0X00,0XCC,0XAA};
	CAN2_TX_PACKET(canid,buf,8);
	delay_ms(100);
	CAN2_TX_PACKET(canid,buf,8);
	delay_ms(100);
	CAN2_TX_PACKET(canid,buf,8);
	delay_ms(100);
}

void LPXX_Stop_Measure(uint16_t canid)
{
	uint8_t buf[8] = {0X55,0X06,0X00,0X00,0X00,0X00,0X88,0XAA};
	CAN1_TX_PACKET(canid,buf,8);
}

void LPXX_Set_Address(uint16_t canid,uint8_t addr)
{
	uint8_t buf[8] = {0X55,0X11,0X00,0X00,0X00,addr,0X88,0XAA};
	buf[6] = crc_high_first(buf+2,6);
	CAN1_TX_PACKET(canid,buf,8);
}

void LPXX_Get_Address(uint16_t canid)
{
	uint8_t buf[8] = {0X55,0X11,0X00,0X00,0X00,0X00,0XAF,0XAA};
	CAN1_TX_PACKET(canid,buf,8);
}

void LPXX_Save_Changed(uint16_t canid)
{
	uint8_t buf[8] = {0X55,0X08,0X00,0X00,0X00,0X00,0X3E,0XAA};
	CAN1_TX_PACKET(canid,buf,8);
}

uint8_t crc_high_first(uint8_t *ptr,uint8_t len)
{
	uint8_t i;
	uint8_t crc = 0x00;
	while(len--)
	{
		crc ^= *ptr++;
		for(i=8;i>0;--i)
		{
			if(crc & 0x80)
			{
				crc = (crc<<1)^0x31;
			}
			else
			{
				crc = (crc<<1);
			}
		}
	}
	return crc;
}

